﻿#include "guild_building_timer.h"

#include "GuildBuilding_struct.h"
#include "GuildModuleBuilding_struct.h"

#include "GuildBuildingUpgradeFinishedNtfData_struct.h"

#include "fwd.h"
#include "timer/service_timer_mgr.hpp"
#include "guild/module/guild_module_loader.hpp"
#include "guild/module/guild_module_saver.hpp"

#include "proxy/guild_service_timer_proxy_mgr.h"

namespace guild_service {

bool GuildBuildingUpgradeTimer::timer_callback(uint64_t usr_data, time_t ms) {
  LOG_INFO("公会升级结束");

  if (type() == detail::timer_type::TIMER_TYPE_ONCE) {
    ServiceTimerMgrSingleton().kill_timer(get_handle());
  }

  GuildModuleBuilding module_building;
  if (!detail::GetGuildModule<GuildModuleBuilding>(
          kGuildServiceTimerName, m_guild_id, kGuildModuleBuildingName,
          module_building)) {
    return false;
  }

  auto &building_dic = module_building.building_dic;
  const auto it = building_dic.find(m_building_id);
  if (it == building_dic.end()) {
    return false;
  }

  it->second.is_upgrading = false;
  it->second.level += 1;

  LOG_INFO("公会建筑升级成功 公会id:%llu 建筑id:%u 等级:%u", m_guild_id, m_building_id, it->second.level);

  if (!detail::SaveGuildModule<GuildModuleBuilding>(kGuildServiceTimerName,
                                               module_building, m_guild_id,
                                               kGuildModuleBuildingName)) {
    return false;
  }
  
  GuildBuildingUpgradeFinishedNtfData data;
  data.building_id = m_building_id;
  data.level = it->second.level;
  GuildServiceTimerProxyMgrSingleton->ForeachProxy(
      [&data](const role_uuid_type role_uuid,
              const std::shared_ptr<GuildClientTimerProxy> proxy_ptr) {
        proxy_ptr->GuildBuildingUpgradeFinishedNtf(data);
      });

  return true;
}

}